package com.lagou.homework1_4;

import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Test03 implements Callable {

    private String srcDir;
    private String destDir;

    public static void main(String[] args) {

        String srcDir = "D:/aaa/";
        String destDir = "D:/bbb/";
        Test03 tct = new Test03(srcDir, destDir);
        FutureTask ft = new FutureTask(tct);

        Thread t1 = new Thread(ft);
        t1.start();

        Object obj = null;
        try {
            obj = ft.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("目录复制成功, 耗时" + obj + "毫秒");
    }

    public Test03(String srcDir, String destDir) {
        this.srcDir = srcDir;
        this.destDir = destDir;
    }

    @Override
    public Object call() throws Exception {
        long start = System.currentTimeMillis();
        copyDir(srcDir, destDir);
        long end = System.currentTimeMillis();
        long time = end - start;
        return time;
    }

    public static void copyDir(String srcDir, String desDir) throws IOException {

        File srcDirFile = new File(srcDir);
        if (!srcDirFile.exists() || !srcDirFile.isDirectory()) {
            return;
        }

        File desDirFile = new File(desDir);
        if (!desDirFile.exists()) {
            desDirFile.mkdir();
        }

        File[] files = srcDirFile.listFiles();
        for (File f : files) {
            if (f.isFile()) {
                copyFile(f, new File(desDir + f.getName()));
            }

            if (f.isDirectory()) {
                copyDir(f.getAbsolutePath() + '/', desDir + f.getName() + '/');
            }
        }

    }

    public static void copyFile(File srcFile, File descFile) {

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            bis = new BufferedInputStream(new FileInputStream(srcFile));
            bos = new BufferedOutputStream(new FileOutputStream(descFile));

            byte[] byteArr = new byte[1024];
            int res = 0;
            System.out.println("将文件" + srcFile.getAbsolutePath() + "复制到" + descFile.getAbsolutePath());
            while ((res = bis.read(byteArr)) != -1) {
                bos.write(byteArr, 0, res);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
